<template>
	<uni-loading v-if="loading"></uni-loading>
	<view class="body" v-else>
		<!--  顶部  -->
		<top-tab :options="stockList" :locationName="locationName" @stockChange="stockChange"
			@handleBarnChoose="handleBarnChoose"></top-tab>
		<view class="add-sale-body" v-if="purchaseList.length === 0" @click="handleOpenSaleScan">
			<span class="tip">请先扫描销售单，之后添加物料。</span>
			<view class="add-sale">
				<view class="add-sale-left">
					<span>扫描销售单</span>
				</view>
				<view class="">
					<uni-icons type="plus-filled" size="30" color="#FF4E74"></uni-icons>
				</view>
			</view>
		</view>
		<!--  列表  -->
		<template v-if="purchaseList && purchaseList.length > 0">
			<view v-for="item in purchaseList">
				<view class="panel" @click="openDetail(item)">
					<view class="panel_title" :class="{error: item.error}">
						<view class="panel_title_left">{{ item.materialName || "" }}</view>
					</view>
					<view class="panel_content">
						<view class="panel_content_row">
							<view class="panel_content_row_item">
								<view class="panel_content_row_item_title">编码：</view>
								<view class="panel_content_row_item_value">{{ item.materialNo || "" }}</view>
							</view>
							<view class="panel_content_row_item">
								<view class="panel_content_row_item_title">规格：</view>
								<view class="panel_content_row_item_value">{{ item.materialSpec || "" }}</view>
							</view>
						</view>
						<view class="panel_content_row">
							<view class="panel_content_row_item">
								<view class="panel_content_row_item_title">生产大类：</view>
								<view class="panel_content_row_item_value">{{ item.prdBigType || "" }}</view>
							</view>
							<view class="panel_content_row_item">
								<view class="panel_content_row_item_title">子项大类：</view>
								<view class="panel_content_row_item_value">{{ item.sonBigType || "" }}</view>
							</view>
						</view>
						<view class="panel_content_row">
							<view class="panel_content_row_item">
								<view class="panel_content_row_item_title">子项小类：</view>
								<view class="panel_content_row_item_value">{{ item.sonSmallType || "" }}</view>
							</view>
							<view class="panel_content_row_item">
								<view class="panel_content_row_item_title">数量：</view>
								<view class="panel_content_row_item_value">{{ item.count || 0 }}{{ item.unit || "" }}
								</view>
							</view>
						</view>
					</view>
					<view class="panel_dashboard">
						<view class="panel_dashboard_item">
							<view class="panel_dashboard_item_number success">{{ item.soldCount || 0 }}</view>
							<view class="panel_dashboard_item_value">已调拨</view>
						</view>
						<view class="panel_dashboard_item">
							<view class="panel_dashboard_item_number default">{{ item.currentCount || 0 }}
							</view>
							<view class="panel_dashboard_item_value">当前数</view>
						</view>
					</view>
				</view>
			</view>
		</template>
		<uni-empty-info v-else label="暂无物料信息"></uni-empty-info>

		<!--  底部按钮  -->
		<view class="footerPanel" v-if="purchaseList.length > 0">
			<view class="footerPanel_body">
				<button @click="handleReset" class="footerBtn reset"><i class="iconfont icon-zhongzhi btn_icon"></i>重置
				</button>
				<button @click="handleWarehousing" class="footerBtn save"><i
						class="iconfont icon-duihao btn_icon"></i>确认
				</button>
				<button @click="handleScanCode" class="footerBtn scan" type="primary"><i
						class="iconfont icon-saomiao btn_icon"></i>扫码
				</button>
			</view>
		</view>

		<!--  操作面板  -->
		<min-action-sheet ref="as"></min-action-sheet>

		<!-- 弹出层 -->
		<WholePopup ref="wholePopup" title="销售单扫描" @confirm="handleSaleConfirm"></WholePopup>
		<MaterialPopupThin ref="scaningPopup" title="物料扫描" type="saleOut" @scanSuccess="handleScanSuccess" @success="addUserAllocationBoxList">
		</MaterialPopupThin>
		<BarnPopup ref="barnPopup" @confirm="onLocationChange"></BarnPopup>
	</view>
</template>
<script>
	import topTab from "@/components/top-tab/top-tab"
	import uniLoading from "../../vBase/components/uni-loading/uni-loading"
	import uniEmptyInfo from "../../vBase/components/uni-empty-info/uni-empty-info"
	import MaterialPopupThin from "@/components/popup/materialPopupThin.vue"
	import BarnPopup from "@/components/popup/barnPopup.vue"
	import WholePopup from "@/components/popup/wholePopup"

	export default {
		components: {
			topTab,
			uniLoading,
			uniEmptyInfo,
			MaterialPopupThin,
			BarnPopup,
			WholePopup
		},
		data() {
			return {
				loading: false,
				purchaseList: [],
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#FF4E74'
					}
				}],
				scaningShow: false,
				scanNo: null,
				isFouce: false,
				stockList: [],
				stockNo: '',
				locationNo: '',
				locationName: "",
				saleId: "",
				materialList: []
			}
		},
		async onLoad() {
			await this.getStockList();
		},
		onUnload() {
			uni.$off('deleteItem');
		},
		mounted() {
			let self = this
			uni.$on('deleteItem', ({
				material,
				success
			}) => {
				uni.showModal({
					title: '提示',
					content: '确认删除吗？',
					success(res) {
						if (res.confirm) {
							const {
								id,
								stockNo,
								materialNo,
								boxNo
							} = material;
							self.$api.deleteSaleAllocationAddMaterialBox({
								boxNo: material.boxNo
							}, {
								loading: true
							}).then((res) => {
								if (!res.res) return;
								self.initList();
								success && success();
							});
						}
					}
				})
			})
		},
		methods: {
			/** 查询仓库*/
			async getStockList() {
				this.loading = true;
				try {
					let {
						res,
						stockList = []
					} = await this.$api.getCustomerStock();
					if (!res) return;
					this.stockList = stockList;
					if (stockList.length) this.stockNo = stockList[0].stockNo;
				} finally {
					this.loading = false;
				}
			},

			/**
			 * 查询列表
			 */
			async initList() {
				let res = await this.$api.getSaleStoreBillSetail({
					billNo: this.saleId
				})
				if (!res.res) return
				this.purchaseList = res.data ?? []
				this.getCurrentListCount()
			},

			/**
			 * 获取列表当前添加的数量
			 */
			async getCurrentListCount() {
				let res = await this.$api.getSaleAllocationAddMaterialCount({
					stockNo: this.stockNo,
					billNo: this.saleId
				})
				if (!res.res) return
				let countObj = res.data ?? {}
				Object.keys(countObj).forEach(v => {
					this.purchaseList.forEach((item, index) => {
						if (v === item.materialNo) {
							item.currentCount = countObj[v]
						}
					})
				})
				this.$forceUpdate()
			},

			/** 重置 */
			handleReset() {
				const self = this
				uni.showModal({
					title: '提示',
					content: '是否重新扫描销售单？',
					success(res) {
						if (res.confirm) {
							self.saleId = ""
							self.purchaseList = []
						}
					}
				})
			},

			/** 立即入库 */
			handleWarehousing() {
				const {
					stockNo,
					purchaseList
				} = this;
				if (!stockNo) {
					uni.showToast({
						title: '请选择仓库',
						icon: 'none'
					});
					return;
				}
				if (!purchaseList || !purchaseList.length) {
					uni.showToast({
						title: '请重新扫描销售单',
						icon: 'none'
					});
					return;
				}
				let index = purchaseList.findIndex(v => {
					return (v.hasOwnProperty('currentCount') && v.currentCount > 0)
				})
				if (index === -1) {
					uni.showToast({
						title: "请扫码添加物料",
						icon: "none"
					})
					return
				}
				const self = this
				uni.showModal({
					title: '提示',
					content: '是否确认调拨？',
					success(res) {
						if (res.confirm) {
							self.$api.saveUserAllocation({
								stockNo: self.stockNo,
								locationNo: self.locationNo,
								allocationType: "sale",
								isSale: true,
								saleBillNo: self.saleId
							}).then(res => {
								if (res.res) {
									uni.showToast({
										title: '操作成功',
										icon: 'none'
									})
									self.saleId = ""
									self.purchaseList = [];
								}
							})
						}
					}
				})
			},

			/**
			 * 选择仓库
			 * @param e
			 */
			stockChange(e) {
				this.stockNo = this.stockList[e].stockNo
			},

			/**
			 * 选择
			 */
			handleBarnChoose() {
				this.$refs.barnPopup.open(this.stockNo);
			},

			/** 扫码 */
			async handleScanCode() {
				if (!this.stockNo) {
					uni.showToast({
						title: "请选择仓库",
						icon: "none"
					})
					return
				}
				if (!this.locationNo) {
					uni.showToast({
						title: "请选择仓位",
						icon: "none"
					})
					return
				}
				this.$refs.scaningPopup.open()
			},

			/** 打开销售单扫码 */
			handleOpenSaleScan() {
				this.$refs.wholePopup.open()
			},

			/**
			 * 扫描销售单号
			 * @param {Object} e
			 */
			handleSaleConfirm(e) {
				this.saleId = e
				this.initList()
			},

			/**
			 * 查看详情
			 */
			async openDetail(material) {
				const {
					materialName,
					materialNo
				} = material
				let {
					res,
					data = []
				} = await this.$api.getSaleAllocationAddMaterialBox({
					materialNo: materialNo,
				}, {
					loading: true
				});
				let dataList = data.map(item => {
					return {
						id: item.id,
						materialName,
						materialNo,
						stockNo: item.stockNo,
						batchNo: item.batchNo,
						boxNo: item.boxNo,
						count: item.count,
						unit: item.unit,
					}
				})
				this.openPopNVue('明细', dataList, null, this.outBoxNo ?? [])
			},

			/**
			 * 扫码成功
			 */
			async handleScanSuccess(e) {
				let res = await this.$api.getUserAllocationBoxList({
					stockNo: this.stockNo,
					boxNo: e,
					locationNo: this.locationNo
				})
				if (!res.res) return
				// 直接关闭面板
				// this.$refs.scaningPopup.close()
				this.materialList = res.hasOwnProperty('data') ? res.data : [res] ?? []
				this.$refs.scaningPopup.initDataList(JSON.stringify(this.materialList))
				// if (this.materialList) {
				// 	this.addUserAllocationBoxList()
				// }
			},

			/**
			 * 添加物料
			 * @param {Object} e
			 */
			async addUserAllocationBoxList(e) {
				try {
					let res = await this.$api.addUserAllocationBoxList({
						boxList: e,
						isSale: true,
						stockNo: e[0].stockNo,
						locationNo: e[0].locationNo,
						boxNo: e[0].boxNo,
						materialNo: e[0].materialNo,
						materialName: e[0].materialName,
						materialSpec: e[0].materialSpec,
						batchNo: e[0].batchNo,
						unit: e[0].unit,
						count: e[0].count,
						exp: e[0].exp,
						produceDate: e[0].produceDate,
						rfid: e[0].rfid,
						allocationType: 'pda',
						saleBillNo: this.saleId
					})

					if (!res.res) return
					this.$refs.scaningPopup.close()
					uni.showToast({
						title: "添加成功",
						icon: "none"
					})
				} finally {
					this.initList()
				}
			},

			/** 选择仓位 */
			onLocationChange(location) {
				this.locationNo = location.locationNo;
				this.locationName = location.locationName;
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import "../../static/css/common";

	.error {
		color: red;
	}

	.add-sale-body {
		.tip {
			margin-top: 20rpx;
			font-size: 26rpx;
			padding-left: 20rpx;
			color: $font-hb;
		}
	}

	.add-sale {
		box-sizing: border-box;
		width: calc(100% - 40rpx);
		margin: 20rpx auto 0 auto;
		padding: 20rpx;
		display: flex;
		height: 120rpx;
		align-items: center;
		justify-content: space-between;
		border-radius: 20rpx;
		background-color: #fff;

		.add-sale-left {
			font-size: 30rpx;
		}
	}
</style>
